import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_utils/flutter_utils.dart';
import 'package:flutter_widget/src/config/color_define.dart';
import 'package:flutter_widget/src/config/font.dart';
import 'package:flutter_widget/src/widget/effect/clip_widget.dart';
import 'package:flutter_widget/src/widget/text/text_format.dart';

/*
可控制的Toast的提示
默认是文本弹窗，从上向下显示，(首页更新提示）
* */
class ToastWidget extends StatefulWidget {
  final ToastController controller; //动画控制
  final Widget body;
  final Widget? toast; //自定义控件，不传则是文本

  const ToastWidget({
    Key? key,
    required this.controller,
    required this.body,
    this.toast,
  }) : super(key: key);

  @override
  _ToastWidgetState createState() {
    return _ToastWidgetState();
  }
}

class _ToastWidgetState extends State<ToastWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  final double _height = AdaptUtil.fitSize(28);
  final double _fontSize = AdaptUtil.fitSize(11);
  final double _textHeight = 1.1;
  final double _leftPadding = AdaptUtil.fitSize(12);

  double get _topPadding => (_height - _fontSize * _textHeight) / 2;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned.fill(child: widget.body),
        ValueListenableBuilder(
          valueListenable: widget.controller.displayNotifier,
          builder: (BuildContext context, bool display, Widget? child) {
            var child = widget.toast ??
                Container(
                  height: _height,
                  alignment: Alignment.center,
                  child: ClipWidget(
                    radius: _height / 2,
                    child: Container(
                      color: FWColorPicker.colorFFDAB27E.withOpacity(0.9),
                      padding: EdgeInsets.only(
                        left: _leftPadding,
                        right: _leftPadding,
                        top: _topPadding,
                        bottom: _topPadding,
                      ),
                      child: TextFormatWidget(
                        widget.controller.text,
                        fontSize: _fontSize,
                        color: FWColorPicker.white.withOpacity(0.9),
                        fontWeight: FWFontTool.w400,
                        maxLine: 1,
                        height: _textHeight,
                      ),
                    ),
                  ),
                );
            return AnimatedPositioned.fromRect(
              rect: widget.controller.currentRect,
              curve: Curves.easeInOutQuart,
              duration: widget.controller.animateDuration,
              child: child,
            );
          },
        ),
      ],
    );
  }
}

class ToastController {
  //过渡动画时间
  late Duration animateDuration = const Duration(milliseconds: 300);

  //显示时间
  late Duration autoHideDuration = const Duration(seconds: 2);

  //位置控制,默认是文本提示框的大小高度
  Rect fromRect;
  Rect toRect;

  /*创建控制器 （以下不设置的话，默认的话是首页更新数据提示的效果）
  * fromRect 从哪个位置开始，不设置默认顶部开始
  * toRect 到哪个位置去
  * animateDuration 动画时长, 不设置则默认300ms
  * autoHideDuration 多久后自动隐藏, 不设置则默认2s后自动隐藏
  * */
  ToastController({
    Rect? fromRect,
    Rect? toRect,
    Duration? animateDuration,
    Duration? autoHideDuration,
  })  : fromRect = fromRect ??
            Rect.fromLTWH(0, -100, Screens.width, AdaptUtil.fitSize(28)),
        toRect = toRect ??
            Rect.fromLTWH(0, 47 / 2 + 30, Screens.width, AdaptUtil.fitSize(28)),
        currentRect = fromRect ??
            Rect.fromLTWH(0, -100, Screens.width, AdaptUtil.fitSize(28)),
        animateDuration = animateDuration ?? const Duration(milliseconds: 300),
        autoHideDuration = autoHideDuration ?? const Duration(seconds: 2);

  late Rect currentRect;
  bool _displayTip = false;
  Timer? _displayTimer;

  //"为你更新 20 条内容"
  String text = "";

  final ValueNotifier<bool> displayNotifier = ValueNotifier<bool>(false);

  ///显示自定义ToastWidget
  ///animateDuration 动画时长，可选
  ///autoHideDuration 多久后自动隐藏，可选
  void show({
    Duration? animateDuration,
    Duration? autoHideDuration,
  }) {
    if (animateDuration != null) this.animateDuration = animateDuration;
    if (autoHideDuration != null) this.autoHideDuration = autoHideDuration;
    if (_displayTip != true) {
      _displayTip = true;
      //播放显示动画
      _displayAnimation();
    }
  }

  ///显示文本，toast文本专用
  ///text，要显示的文本
  ///animateDuration 动画时长，可选
  ///autoHideDuration 多久后自动隐藏
  void showText({
    required String text,
    Duration? animateDuration,
    Duration? autoHideDuration,
  }) {
    if (animateDuration != null) this.animateDuration = animateDuration;
    if (autoHideDuration != null) this.autoHideDuration = autoHideDuration;
    this.text = text;
    if (_displayTip != true) {
      _displayTip = true;
      //播放显示动画
      _displayAnimation();
    }
  }

  //可手动控制消失
  void dismiss() {
    if (_displayTip == true) {
      _displayTip = false;
      //播放隐藏动画
      _hiddenAnimation();
    }
  }

  void _displayAnimation() {
    currentRect = toRect;
    displayNotifier.value = true;
    _displayTimer?.cancel();
    _displayTimer = Timer(autoHideDuration, () {
      dismiss();
    });
  }

  void _hiddenAnimation() {
    currentRect = fromRect;
    displayNotifier.value = false;
  }
}
